#include "Saveplate.h"

SaveDate::SaveDate(QString driver) {
    InitPlateDb(driver);
}

SaveDate::~SaveDate() {
    platedb.close();
}

bool SaveDate::InsertPlate(Info* info) {
    if (!info) {
        qDebug() << "Data insert fatal";
        return false;
    }

    if (!platedb.open()) {
        qDebug() << "Error: Connection with database failed";
        return false;
    }

    // 处理QImage
    QBuffer buffer;
    buffer.open(QIODevice::WriteOnly);
    QImageWriter writer(&buffer, "JPG");
    writer.write(info->image);
    QByteArray imageData = buffer.buffer();
    buffer.close();

    QSqlQuery query;
    QString id = QString(info->name.c_str());
    QString entryTime = info->in_time;
    // QString exitTime = "";  // 或者留空如果尚未出场

    // 准备SQL语句，注意使用占位符来防止SQL注入
    QString sql = R"(  
            INSERT INTO plates (place, entry_time, image, time)  
                VALUES (?, ?, ?, ?))";

    // 绑定参数
    query.prepare(sql);
    query.addBindValue(id);
    query.addBindValue(entryTime);
    // query.addBindValue(exitTime);
    query.addBindValue(imageData);
    query.addBindValue(info->starttime);

    // 执行SQL语句
    if (!query.exec()) {
        // 处理SQL执行失败的情况
        qDebug() << "Error inserting data into the database: " << query.lastError().text();
        return false;
    }
    qDebug() << "Data inserted successfully";
    platedb.close();
    return true;
}

bool SaveDate::DeletePlate(const std::string& str) {
    if (str.empty()) {
        qDebug() << "Data delete fatal";
        return false;
    }

    if (!platedb.open()) {
        qDebug() << "Error: Connection with database failed";
        return false;
    }

    QSqlQuery query;
    QString idToDelete = QString(str.c_str());
    // 准备SQL删除语句
    QString sql = R"(DELETE FROM plates WHERE place = ?)";
    // 绑定参数并执行SQL语句
    query.prepare(sql);
    query.addBindValue(idToDelete);
    if (!query.exec()) {
        // 处理SQL执行失败的情况
        qDebug() << "Error deleting data from the database:" << query.lastError().text();
        return false;
    }
    qDebug() << "Data deleted successfully";
    platedb.close();

    return true;
}

bool SaveDate::SelectPlate(const std::string& str) {
    if (str.empty()) {
        qDebug() << "Data select fatal";
        return false;
    }

    if (!platedb.open()) {
        qDebug() << "Error: Connection with database failed";
        return false;
    }

    QSqlQuery query;
    query.prepare("SELECT entry_time, image FROM plates WHERE id = :place");
    query.bindValue(":place", QString(str.c_str()));

    if (query.exec() && query.next()) {
        return true;
    }

    return false;
}

QSqlQueryModel* SaveDate::GetModel() {
    if (!platedb.open()) {
        qDebug() << "Error: Connection with database failed";
        return NULL;
    }

    // QSqlQuery query;
    // query.prepare("SELECT place, entry_time FROM plates");
    // if (query.exec()) {
    //     while (query.next()) {
    //         qDebug() << query.value(0).toString() << " " << query.value(1).toString();
    //     }
    // }

    QSqlQueryModel* model = new QSqlQueryModel;
    // model->setQuery("select * from plates");
    model->setQuery("select place, entry_time from plates");
    platedb.close();

    return model;
}

void SaveDate::InitPlateDb(QString driver) {
    if (QSqlDatabase::contains("plate.db")) {
        platedb = QSqlDatabase::database("plate.db");
    }
    platedb = QSqlDatabase::addDatabase(driver);
    platedb.setDatabaseName("plate.db");

    // while (!createTable()) {
    // }
    createTable();
}

bool SaveDate::createTable() {
    if (!platedb.open()) {
        qDebug() << "Error : Connection with platedb.db failed";
        return false;
    }

    // 创建一个QSqlQuery对象
    QSqlQuery query;
    // 准备SQL语句来创建表
#if 0
    QString sql = R"(
        CREATE TABLE IF NOT EXISTS plates (
            palce TEXT PRIMARY KEY,
            entry_time TEXT NOT NULL,
            exit_time TEXT,
            image BLOB
        )
    )";
#else
    QString sql = R"(  
        CREATE TABLE IF NOT EXISTS plates (  
            place TEXT PRIMARY KEY,  
            entry_time TEXT NOT NULL,   
            image BLOB,
            time TIMESTAMP
        )  
    )";
#endif
    // 执行SQL语句
    if (!query.exec(sql)) {
        qDebug() << "Error: Unable to create table";
        qDebug() << query.lastError().text();
        return false;
    }
    // qDebug() << "Table created successfully";

    platedb.close();
    return true;
}

void SaveDate::InitDate(Plates* places) {
    if (!places) {
        return;
    }

    if (!platedb.open()) {
        qDebug() << "Error: Connection with database failed";
        return;
    }

    QSqlQuery query;
    query.prepare("SELECT * FROM plates");

    if (query.exec()) {
        QByteArray imageDate;
        while (query.next()) {
            auto* info = new Info;
            info->name = query.value(0).toString().toStdString();
            info->in_time = query.value(1).toString();
            imageDate = query.value(2).toByteArray();

            // QBuffer buffer(&imageDate);
            // buffer.open(QIODevice::ReadOnly);
            // QImageReader reader(&buffer, "PNG");
            // info->image = reader.read();
            // 读取失败
            //
            info->image.loadFromData(imageDate);

            info->starttime = query.value(3).toLongLong();

            // buffer.close();

            places->push_plate(info);
        }
    }
}
